#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Zerogpt API检测模块
Zerogpt API Detection Module

使用Zerogpt API检测内容是否为大语言模型生成
"""

import http.client
import logging
import json
from typing import Dict, Optional, Tuple
from config import Config

logger = logging.getLogger(__name__)

class ZerogptDetector:
    """Zerogpt API检测器"""
    
    def __init__(self, api_key: Optional[str] = None):
        """
        初始化Zerogpt检测器
        
        Args:
            api_key: Zerogpt API密钥，如果为None则使用默认API key
        """
        # 使用提供的API key
        self.api_key = api_key or "272297c6aemsh826a07ff7b8b8b7p110b27jsncc056fe79a23"
        self.host = "zerogpt.p.rapidapi.com"
        self.timeout = Config.get_http_config().get('timeout', 30)
        self.max_retries = Config.get_http_config().get('max_retries', 3)
        
        # 检测阈值
        thresholds = Config.get_detection_thresholds()
        self.ai_probability_high = thresholds.get('ai_probability_high', 0.7)  # 降低阈值，70%以上认为是AI生成
        self.ai_probability_low = thresholds.get('ai_probability_low', 0.3)
        
    def detect_ai_content(self, content: str) -> Dict:
        """
        使用Zerogpt API检测内容是否由AI生成
        
        Args:
            content: 待检测的内容
            
        Returns:
            Dict: 包含检测结果的字典
        """
        if not self.api_key:
            logger.warning("Zerogpt API密钥未配置，使用本地检测")
            return self._local_ai_detection(content)
        
        try:
            # 准备请求数据
            payload = {
                'input_text': content
            }
            
            headers = {
                'X-RapidAPI-Key': self.api_key,
                'X-RapidAPI-Host': self.host,
                'Content-Type': 'application/json'
            }
            
            # 记录 API 调用开始
            logger.info(f"开始调用 Zerogpt API...")
            logger.info(f"API Host: {self.host}")
            logger.info(f"API Key: {self.api_key[:20]}...")
            logger.info(f"请求数据: {json.dumps(payload, ensure_ascii=False)[:100]}...")
            
            # 使用http.client发送请求
            conn = http.client.HTTPSConnection(self.host)
            conn.request("POST", "/api/v1/detectText", json.dumps(payload), headers)
            
            response = conn.getresponse()
            result = json.loads(response.read().decode())
            
            logger.info(f"Zerogpt API 响应状态aaa: {response.status}")
            logger.info(f"Zerogpt API 响应内容: {json.dumps(result, ensure_ascii=False)[:200]}...")
            
            if response.status == 200:
                logger.info("Zerogpt API 调用成功，使用 API 结果")
                return self._process_api_response(result, content)
            else:
                logger.error(f"Zerogpt API请求失败: {response.status} - {result}")
                logger.info("回退到本地检测")
                return self._local_ai_detection(content)
                
        except Exception as e:
            logger.error(f"Zerogpt API检测失败: {str(e)}")
            logger.info("由于 API 调用异常，回退到本地检测")
            return self._local_ai_detection(content)
    
    def _process_api_response(self, api_result: Dict, original_content: str) -> Dict:
        """
        处理API响应结果
        
        Args:
            api_result: API返回的原始结果
            original_content: 原始内容
            
        Returns:
            Dict: 处理后的检测结果
        """
        # 检查API响应格式
        if api_result.get('success') and 'data' in api_result:
            # 新格式：{"success": true, "data": {"is_human_written": 22.07, "is_gpt_generated": 77.93, ...}}
            data = api_result['data']
            ai_probability = data.get('is_gpt_generated', 0.0) / 100.0  # 转换为0-1范围
            human_probability = data.get('is_human_written', 0.0) / 100.0
            
            # 确定内容类型
            if ai_probability > human_probability:
                content_type = 'ai_generated'
            elif ai_probability < human_probability:
                content_type = 'human_written'
            else:
                content_type = 'uncertain'
            
            # 提取其他信息
            feedback_message = data.get('feedback_message', '')
            gpt_sentences = data.get('gpt_generated_sentences', [])
            
            return {
                'success': True,
                'ai_probability': ai_probability,
                'human_probability': human_probability,
                'content_type': content_type,
                'confidence': max(ai_probability, human_probability),  # 使用较高的概率作为置信度
                'model_used': 'zerogpt_api',
                'detection_method': 'zerogpt_api',
                'original_content_length': len(original_content),
                'feedback_message': feedback_message,
                'gpt_generated_sentences': gpt_sentences,
                'api_response': api_result
            }
        else:
            # 旧格式兼容
            ai_probability = api_result.get('ai_probability', 0.0)
            
            # 确定内容类型
            if ai_probability > self.ai_probability_high:
                content_type = 'ai_generated'
            elif ai_probability < self.ai_probability_low:
                content_type = 'human_written'
            else:
                content_type = 'uncertain'
            
            # 提取其他可能的指标
            confidence = api_result.get('confidence', 0.0)
            model_used = api_result.get('model_used', 'unknown')
            
            return {
                'success': True,
                'ai_probability': ai_probability,
                'content_type': content_type,
                'confidence': confidence,
                'model_used': model_used,
                'detection_method': 'zerogpt_api',
                'original_content_length': len(original_content),
                'api_response': api_result
            }
    
    def _local_ai_detection(self, content: str) -> Dict:
        """
        本地AI检测（当API不可用时）
        
        Args:
            content: 待检测的内容
            
        Returns:
            Dict: 本地检测结果
        """
        logger.info("使用本地启发式检测方法")
        import re
        
        # AI生成内容的特征模式
        ai_indicators = [
            # 中文AI特征
            r'根据.*分析',
            r'综上所述',
            r'总的来说',
            r'因此.*',
            r'基于.*研究',
            r'研究表明',
            r'数据.*显示',
            r'统计.*表明',
            r'专家.*表示',
            r'报告.*指出',
            r'调查.*显示',
            r'研究.*发现',
            r'分析.*表明',
            r'结果.*显示',
            r'结论.*是',
            
            # 英文AI特征
            r'according to.*',
            r'research shows',
            r'studies indicate',
            r'data suggests',
            r'experts say',
            r'analysis reveals',
            r'findings show',
            r'results indicate',
            r'in conclusion',
            r'therefore',
            r'thus',
            r'hence',
            r'consequently',
            r'as a result',
            r'it is clear that'
        ]
        
        # 计算AI特征出现次数
        ai_count = 0
        total_indicators = len(ai_indicators)
        
        for pattern in ai_indicators:
            if re.search(pattern, content, re.IGNORECASE):
                ai_count += 1
        
        # 计算AI概率
        ai_probability = min(ai_count / total_indicators * 2, 0.9)
        
        # 考虑内容长度和复杂度
        words = content.split()
        if len(words) < 50:
            ai_probability *= 0.8  # 短内容可能不太准确
        
        # 检测重复模式
        sentences = re.split(r'[。！？.!?]', content)
        unique_sentences = set()
        for sentence in sentences:
            if len(sentence.strip()) > 10:
                unique_sentences.add(sentence.strip())
        
        if len(sentences) > 0:
            repetition_rate = 1 - (len(unique_sentences) / len(sentences))
            ai_probability += repetition_rate * 0.1
        
        ai_probability = min(ai_probability, 1.0)
        
        # 确定内容类型
        if ai_probability > self.ai_probability_high:
            content_type = 'ai_generated'
        elif ai_probability < self.ai_probability_low:
            content_type = 'human_written'
        else:
            content_type = 'uncertain'
        
        return {
            'success': True,
            'ai_probability': ai_probability,
            'content_type': content_type,
            'confidence': 0.7,  # 本地检测的置信度较低
            'model_used': 'local_heuristic',
            'detection_method': 'local_heuristic',
            'original_content_length': len(content),
            'ai_indicators_found': ai_count,
            'total_indicators': total_indicators
        }
    
    def batch_detect(self, contents: list) -> list:
        """
        批量检测多个内容
        
        Args:
            contents: 内容列表
            
        Returns:
            list: 检测结果列表
        """
        results = []
        for content in contents:
            result = self.detect_ai_content(content)
            results.append(result)
        return results
    
    def get_detection_stats(self, results: list) -> Dict:
        """
        获取检测统计信息
        
        Args:
            results: 检测结果列表
            
        Returns:
            Dict: 统计信息
        """
        if not results:
            return {}
        
        total_count = len(results)
        ai_generated = sum(1 for r in results if r.get('content_type') == 'ai_generated')
        human_written = sum(1 for r in results if r.get('content_type') == 'human_written')
        uncertain = sum(1 for r in results if r.get('content_type') == 'uncertain')
        
        avg_ai_probability = sum(r.get('ai_probability', 0) for r in results) / total_count
        
        return {
            'total_count': total_count,
            'ai_generated_count': ai_generated,
            'human_written_count': human_written,
            'uncertain_count': uncertain,
            'ai_generated_ratio': ai_generated / total_count,
            'human_written_ratio': human_written / total_count,
            'uncertain_ratio': uncertain / total_count,
            'average_ai_probability': avg_ai_probability
        } 